﻿<?php
class UpdateAction extends CommonAction {

	public function index() {
		$path = SITE_DATA_PATH .'/';
		$versionInfo = F ( 'version', '', $path);
		/* foreach ($versionInfo as $k => $v) {
			if($v['status'] != '0') {
				unset($versionInfo[$k]);
			}
		}
		F('version',$versionInfo,$path); */
		$keyarr = array_keys ( $versionInfo );
		$url = SERVER_URL.'/index.php?app=admin&m=SearchUpdateVersion&a=searchUpdateVersion';
		$list = $this->getServerVersionInfo($path.'version.php',$keyarr,$path,$url);
		foreach ( $versionInfo as $k=>$v ) {
			if($k!=0 && $v['status']!=1)
				$list [$k] = $versionInfo [$k];
			if($k!=0 && $v['status']==1) 
				$xx [$k] = $versionInfo[$k];
		}
		$nowkey = 0;
		foreach ($list as $k=>$vo){
			if($nowkey==0 || $nowkey>$k){
				$nowkey = $k;
				$pretitle = $vo['title'];
			}
		}
		$this->assign ( 'list', $list );
		$this->assign('listold',array_pop($xx));
		$this->assign ( 'nowkey', $nowkey );
		$this->assign ( 'pretitle', $pretitle );
		$this->getIsUpdateApp();
		$this->getIsUpdatePlugin();
		$this->display();
	}
	
	/**
	 * 后台首页 查看系统信息
	 * Create Data <2013-10-15>
	 */
	public function main() {
		/*$path = SITE_DATA_PATH .'/';
		$versionInfo = F ( 'version', '', $path);
		/* foreach ($versionInfo as $k => $v) {
		 if($v['status'] != '0') {
		unset($versionInfo[$k]);
		}
		}
		F('version',$versionInfo,$path); */
		/*$keyarr = array_keys ( $versionInfo );
		$url = SERVER_URL.'/index.php?app=admin&m=SearchUpdateVersion&a=searchUpdateVersion';
		$list = $this->getServerVersionInfo($path.'version.php',$keyarr,$path,$url);
		foreach ( $versionInfo as $k=>$v ) {
			if($k!=0 && $v['status']!=1)
				$list [$k] = $versionInfo [$k];
			if($k!=0 && $v['status']==1)
				$xx [$k] = $versionInfo[$k];
		}
		$nowkey = 0;
		foreach ($list as $k=>$vo){
			if($nowkey==0 || $nowkey>$k){
				$nowkey = $k;
				$pretitle = $vo['title'];
			}
		}
		$this->assign ( 'list', $list );
		$this->assign('listold',array_pop($xx));
		$this->assign ( 'nowkey', $nowkey );
		$this->assign ( 'pretitle', $pretitle );
		$this->getIsUpdateApp();
		$this->getIsUpdatePlugin();*/
		$info = array (
				L ( 'operatingSystem' ) => PHP_OS,
				L ( 'operatingEnvironment' ) => $_SERVER ["SERVER_SOFTWARE"],
				L ( 'phpOperationMode' ) => php_sapi_name (),
				L ( 'uploadAttachmentLimits' ) => ini_get ( 'upload_max_filesize' ),
				L ( 'executionTimeLimit' ) => ini_get ( 'max_execution_time' ) . L ( 'second' ),
				L ( 'serverTime' ) => date ( 'Y年n月j日 H:i:s' ),
				L ( 'beiJingTime' ) => gmdate ( 'Y年n月j日 H:i:s', time () + 8 * 3600 ),
				L ( 'serverDomainName' ) => $_SERVER ['SERVER_NAME'] . ' [ ' . gethostbyname ( $_SERVER ['SERVER_NAME'] ) . ' ]',
				L ( 'remainingSpace' ) => round ( (@ disk_free_space ( "." ) / (1024 * 1024)), 2 ) . 'M'
		);
		$this->assign ( 'info', $info );
		$this->display();
	}
	
	/**
	 * 获取需要更新的应用版本
	 * M2
	 */
	private function getIsUpdateApp() {
		//获取当前应用的版本
		$apps = M('app')->field('app_name,version')->select();
		foreach ($apps as $v) {
			$x[$v['app_name']] = $v['version'];
		}
		$appUrl = SERVER_URL.'/index.php?app=admin&m=SearchUpdateVersion&a=searchUpdateAppVersion';
		$result = $this->curlGetInfo($appUrl,$x);
		$this->assign('x',$x);
		$this->assign('result',$result);
	}
	
	/**
	 * 获取需要更新的插件版本	
	 * M2
	 */
	private function getIsUpdatePlugin() {
		$apps = M('addons')->field('name,version')->select();
		foreach ($apps as $v) {
			$xs[$v['name']] = $v['version'];
		}
		$pluginUrl = SERVER_URL.'/index.php?app=admin&m=SearchUpdateVersion&a=searchUpdatePluginVersion';
		$results = $this->curlGetInfo($pluginUrl,$xs);
		$this->assign('xs',$xs);
		$this->assign('resultPlugin',$results);
	}
	
	/**
	 * 远程获取信息	
	 * M2
	 */
	private function curlGetInfo($url,$x) {
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($x,'&'));
		$result = curl_exec($curl);
		curl_close($curl);
		$result = unserialize($result);
		return $result;
	}
	
	/**
	 * 检查目录权限
	 * M2
	 */
	private function checkWritable() {
		$file = array('api','apps','config','data','extends','ocean','Plugins','URLRewrite');
		$filearr = array();
		foreach ($file as $v) {
			$filename = SITE_PATH.'/'.$v;
			if(is_dir($filename)) {
				if(!is_writable($filename)) {
					$filearr[] = $v;
				}
			}
		}
		$this->assign('filearr',$filearr);
	}
	
	/**
	 * 解压	
	 * M2
	 */
	public function extract() {
		import('@.ORG.pclzip','','.lib.php');
		if($_POST) {
			$zip = SITE_DATA_PATH . '/download/'.$_POST['zip'];
			$filename = new PclZip($zip);
			$file = './data/download/'.rtrim($_POST['zip'],'.zip');
			$m = $filename->extract(PCLZIP_OPT_PATH,$file);
			if($m) {
				echo 1;
			} else {
				echo $filename->errorInfo(true);
			}
		}
	}
	
	/**
	 * 获取服务器版本信息	
	 * M2
	 */
	private function getServerVersionInfo($file,$keyarr,$path,$url) {
		$contents = file_get_contents ($url);
		$contents = json_decode ($contents, true);
		$getkey = array();
		foreach ($contents as $k => $c) {
			$getkey[] = $c['date'];
		}
		$result = array_diff ( $getkey, $keyarr );
		foreach ( $result as $d ) {
			$list [$d] = $contents [$d];
			$arr = $contents[$d];
			$arr ['status'] = 0;
			if(file_exists($file)) {
				$vs = F ( 'version', '', $path );
			}
			$vs [$d] = $arr;
			F ( 'version', $vs, $path );
		}
		return $list;
	}
	
	/**
	 * 准备下载安装包	
	 * M2
	 */
	public function readyDownload() {
		if($_POST['key'] && !empty($_POST['key'])) {
			$this->updateStatus($_POST['key'],2);
		}
	}
	
	/**
	 * 开始下载安装包	
	 * M2
	 */
	public function dowload() {
		set_time_limit(0);
		$downloadPath = SITE_DATA_PATH.'/download/';
		$packageURL = SERVER_URL.'/update/'.$_POST['zip'];
		if (! is_dir ( $downloadPath ))
			$res = mkdir ( $downloadPath, 0777, true );
		$file = fopen ( $packageURL, "rb" );
		if($file) {
			$newfname = $downloadPath . basename ( $packageURL );
			$newf = fopen ( $newfname, "wb" );
			if($newf) {
				while ( ! feof ( $file ) ) {
					fwrite ( $newf, fread($file,1024 * 8), 1024 * 8 );
					ob_flush ();
					flush ();
				}
				fclose ( $file );
				fclose ( $newf );
				echo 1;
			}
		} else {
			echo 0;
		}
	}
	
	/**
	 * 更新版本状态	
	 * M2
	 */
	public function updateStatus($key,$status) {
		$path = SITE_DATA_PATH.'/';
		$vs = F('version', '', $path);
		foreach ($vs as $k => &$v) {
			if($k != $key) continue;
			$v['status'] = $status;
		}
		F('version', $vs,$path);
	}
	
	/**
	 * 更新文件	
	 * M2
	 */
	public function copyfile() {
		if($_POST) {
			$updateFile = SITE_DATA_PATH.'/download/'.rtrim($_POST['zip'],'.zip');
			$sourceFile = SITE_PATH;
			import('ORG.Io.Dir');
			Dir::copyDir($updateFile,$sourceFile);
			echo 1;
		}
	}
	
	/**
	 * 更新应用文件	
	 * M2
	 */
	public function copyAppFile() {
		if($_POST) {
			$key = $_POST['key'];
			$updateAppFile = SITE_DATA_PATH.'/download/'.rtrim($_POST['zip'],'.zip');
			$sourceAppFile = APPS_PATH.'/'.$key;
			import('ORG.Io.Dir');
			Dir::copyDir($updateAppFile,$sourceAppFile);
			echo 1;
		}
	}
	
	/**
	 * 更新插件文件	
	 * M2
	 */
	public function copyPluginFile() {
		if($_POST) {
			$key = $_POST['key'];
			$updateAppFile = SITE_DATA_PATH.'/download/'.rtrim($_POST['zip'],'.zip');
			$sourceAppFile = SITE_PATH.'/Plugins/'.$key;
			import('ORG.Io.Dir');
			Dir::copyDir($updateAppFile,$sourceAppFile);
			echo 1;
		}
	}
	
	/**
	 * 更新数据库信息	
	 * M2
	 */
	public function sqlInfo() {
		if($_POST) {
			$key = $_POST['key'];
			$updateAppSqlFile = SITE_PATH.'/config/'.$key.'.sql';
			if(file_exists($updateAppSqlFile)) {
				$res = M('')->executeSqlFile($updateAppSqlFile);
				echo !empty($res) ? 0 : 1;
			} else {
				echo 1;
			}
		}
	}
	
	/**
	 * 更新应用数据库信息	
	 * M2
	 */
	public function appSqlInfo() {
		if($_POST) {
			$key = $_POST['key'];
			$version = $_POST['version'];
			$updateAppSqlFile = APPS_PATH.'/'.$key.'/Appinfo/'.$version.'.sql';
			if(file_exists($updateAppSqlFile)) {
				$res = M('')->executeSqlFile($updateAppSqlFile);
				echo !empty($res) ? 0 : 1;
			} else {
				echo 1;
			}
		}
	}
	
	/**
	 * 更新插件数据库信息
	 * M2
	 */
	public function pluginSqlInfo() {
		if($_POST) {
			$key = $_POST['key'];
			$version = $_POST['version'];
			$updateAppSqlFile = SITE_PATH.'/Plugins/'.$key.'/sql/'.$version.'.sql';
			if(file_exists($updateAppSqlFile)) {
				$res = M('')->executeSqlFile($updateAppSqlFile);
				echo !empty($res) ? 0 : 1;
			} else {
				echo 1;
			}
		}
	}
	
	/**
	 * 完成更新
	 * M2
	 */
	public function noRuntime() {
		$path = SITE_DATA_PATH.'/';
		$vs = F('version', '', $path);
		foreach ( $vs as $k => &$v ) {
			if ($v ['status'] != 2)
				continue;
			$v ['status'] = 1;
		}
		F ( 'version', $vs, $path );
		$this->delDownloadFile($_POST['zip']);
		echo 1;
	}
	
	/**
	 * 删除下载文件和加压文件	
	 * M2
	 */
	private function delDownloadFile($zip) {
		$filepath = SITE_DATA_PATH.'/download/'.rtrim($zip,'.zip');
		$zippath = SITE_DATA_PATH.'/download/'.$zip;
		import('ORG.Io.Dir');
		if(file_exists($filepath)) Dir::delDir($filepath);
		if(file_exists($zippath)) unlink($zippath);
	}
	
	/**
	 * 完成应用更新	
	 * M2
	 */
	public function noAppRuntime() {
		if($_POST) {
			$key = $_POST['key'];
			$data['version'] = $_POST['version'];
			M('app')->where("app_name='$key'")->save($data);
			A('Index')->cleanRuntime2();
			$this->delDownloadFile($_POST['zip']);
			echo 1;
		}
	}
	
	/**
	 * 完成插件更新	
	 * M2
	 * @param
	 */
	public function noPluginRuntime() {
		if($_POST) {
			$key = $_POST['key'];
			$data['version'] = $_POST['version'];
			M('addons')->where("name='$key'")->save($data);
			A('Index')->cleanRuntime2();
			$this->delDownloadFile($_POST['zip']);
			echo 1;
		}
	}
}
?>